<?php

namespace Biz\service\admin;

use Biz\cache\Activitys;
use Biz\model\activity\AllActivityGoods;
use Biz\model\activity\AllActivitySku;
use Biz\model\activity\LimitTimeRobbing as mLimitTimeRobbing;
use Biz\model\activity\LimitTimeRobbingSku;
use Biz\model\GoodsBasicInfo;
use Biz\model\GoodsSku;
use Biz\model\ShopBasicInfo;
use Biz\service\activity\AllActivityInfo;
use Biz\service\GoodsDetail;
use Biz\model\activity\FlashSale as mFlashSale;
use Biz\model\activity\AllActivitySku as mAllActivitySku;
use Biz\pockets\constInterface\ActivityInfo;
use Biz\service\Sku;

class LimitTimeRob
{

    const ADMIN_STATUS_NO_START = 1;

    const ADMIN_STATUS_START = 2;

    const ADMIN_STATUS_END = 3;


    const ADMIN_STATUS_MAP = [
        self::ADMIN_STATUS_NO_START => '未开始',
        self::ADMIN_STATUS_START => '进行中',
        self::ADMIN_STATUS_END => '已结束',
    ];

    public static $error_msg = '';

    public static function getMsg()
    {
        return self::$error_msg;
    }

    private static function setMsg($msg)
    {
        self::$error_msg = $msg;
    }


    public static function SearchSku($goods_id, $start_time, $end_time)
    {
        $skuinfo = GoodsDetail::SearchSku($goods_id, false);
        $goodsInfo = GoodsDetail::formatBasicInfos([$goods_id])[$goods_id];
        $robSkus = LimitTimeRobbingSku::getInfo([
            'goods_id' => $goods_id,
            'start_time' => $start_time,
            'end_time' => $end_time,
            'status' => [
                LimitTimeRobbingSku::STATUS_NORMAL,
            ]
        ]);
        $robSkus = array_column($robSkus, null, 'sku_id');

        foreach ($skuinfo['sku_info'] as &$sku) {
            if (isset($robSkus[$sku['sku_id']])) {
                $sku['promo_stock'] = $robSkus[$sku['sku_id']]['promo_stock'];
            } else {
                $sku['promo_stock'] = 0;
            }

        }
        $skuinfo['goodsinfo'] = $goodsInfo;
        return $skuinfo;

    }


    public static function getLists($start_time, $end_time)
    {
        $robInfos = mLimitTimeRobbing::selectInfos($start_time, $end_time);
        $robbing_ids = array_column($robInfos, 'id');
        $goods_ids = array_column($robInfos, 'goods_id');
        $robSkuInfos = LimitTimeRobbingSku::getInfosByRobID($robbing_ids);
        $sku_ids = [];
        foreach ($robSkuInfos as $robSkuInfo) {
            $sku_ids = array_merge($sku_ids, array_column($robSkuInfo, 'sku_id'));
        }

        $skuInfos = GoodsSku::getInfoList($sku_ids);

        $goodsInfos = GoodsDetail::formatBasicInfos($goods_ids);

        foreach ($robInfos as &$robInfo) {
            $robInfo['sku_infos'] = [];
            foreach ($robSkuInfos[$robInfo['id']] as $robSkuInfo) {

                $skuinfo = $skuInfos[$robSkuInfo['sku_id']];
                $skuinfo['start_stock'] = $robSkuInfo['start_stock'];
                $robInfo['sku_infos'][] = $skuinfo;
            }

            $robInfo['goods_infos'] = $goodsInfos[$robInfo['goods_id']];
        }

        return $robInfos;
    }

    public static function updateLimitRob($data = [], $where = [])
    {
        if (!isset($data['status'])) {
            $data['status'] = mLimitTimeRobbing::STATUS_NORMAL;
            $data['describe'] = trim($data['describe']);
			$data['order'] = trim($data['order']);
            $data['commission'] = ($data['commission'] == NULL) ? -1.0 : $data['commission'];
        }

        $ids = [];
        if (isset($data['ids'])) {
            $ids = $data['ids'];
            unset($data['ids']);
        }
        if (self::is_can_save($data['start_time'], $data['end_time'], ['id[!]' => $ids])) {
        	if (mb_strlen($data['describe']) > 20) {
				self::setMsg('卖点不能超过20个中文字符');
				return false;
			}
            return mLimitTimeRobbing::updateRobbing($data, $where);
        } else {
            self::setMsg('时间设置有误');
            return false;
        }
    }


    public static function searchLimitRob($fields = [])
    {
        $where = [];

        if ($fields['date_start'] && $fields['date_end']) {
			$where['start_time[>]'] = $fields['date_start'];
			$where['end_time[<]'] = $fields['date_end'];
		}

        $where['status'] = mLimitTimeRobbing::STATUS_NORMAL;
        if ($fields['keyword1']) {
            if ($fields['shop_search_type'] == 'uid') {
                $where['shop_id'] = $fields['keyword1'];
            } else if ($fields['shop_search_type'] == 'name') {
                $shop_ids = mLimitTimeRobbing::getFiledsByFilter(['shop_id'], $where);

                $shop_ids = ShopBasicInfo::selectFieldsByFilter(['shop_id'], [
                    'shop_id' => $shop_ids,
                    'name[~]' => $fields['keyword1']
                ]);

                $where['shop_id'] = $shop_ids;
            }
        } else if ($fields['keyword2']) {
            if ($fields['goods_search_type'] == 'goods_id') {
                $where['goods_id'] = $fields['keyword2'];
            } else if ($fields['goods_search_type'] == 'goods_name') {
                $goods_ids = mLimitTimeRobbing::getFiledsByFilter(['goods_id'], $where);

                $goods_ids = GoodsBasicInfo::getFieldsByFilter(['goods_id'], [
                    'goods_id' => $goods_ids,
                    'title[~]' => $fields['keyword2']
                ]);
                $where['goods_id'] = $goods_ids;
            }
        }


        unset($where['start_time[>]']);
        unset($where['end_time[>]']);
        unset($where['status']);

        list($count, $infos) = mLimitTimeRobbing::getListByTime($where, $fields['date_start'], $fields['date_end']);

        $infoList = [];
        foreach ($infos as $info) {
            $infoList[$info['start_time'] . "_" . $info['end_time']][] = $info;
        }

        $results = array_map(function ($info) {
            $result = [];
            $result['shop_num'] = count(array_unique(array_column($info, 'shop_id')));
            $result['goods_num'] = count(array_unique(array_column($info, 'goods_id')));
            $robbingSKus = LimitTimeRobbingSku::select('*', [
                'robbing_id' => array_column($info, 'id'),
                'status' => LimitTimeRobbingSku::STATUS_NORMAL
            ]);

            $result['sku_num'] = count(array_unique(array_column($robbingSKus, 'sku_id')));

            $result['stock_num'] = array_sum(array_column($robbingSKus, 'promo_stock'));

            $result['admin_status'] = self::getAdminStatus($info[0]['start_time'], $info[0]['end_time']);

            $result['admin_status_des'] = self::ADMIN_STATUS_MAP[$result['admin_status']];

            return $result;
        }, $infoList);

        return $results;

    }


    private static function getAdminStatus($start_time, $end_time)
    {
        $now_date = date("Y-m-d H:i:s");

        if ($now_date < $start_time) {
            return self::ADMIN_STATUS_NO_START;
        } elseif ($start_time < $now_date && $end_time > $now_date) {
            return self::ADMIN_STATUS_START;
        } elseif ($end_time < $now_date) {
            return self::ADMIN_STATUS_END;
        }
    }

    public static function del($start_time, $end_time, $goods_id = 0)
	{
		if ($goods_id) {
			$limitInfo = mLimitTimeRobbing::getInfo($start_time, $end_time, $goods_id);
			AllActivityInfo::admDelActivityByGoodsId($limitInfo['id'], ActivityInfo::ACTIVITY_TYPE_LIMIT_TIME_ROB, $limitInfo['goods_id'], AllActivityInfo::ALL_ACTIVITY_TYPE_FLASH_SALE);
			$limitRobInfos = [$limitInfo];
		} else {
			$limitRobInfos = mLimitTimeRobbing::selectInfos($start_time, $end_time);

			foreach ($limitRobInfos as $limitRobInfo) {
				AllActivityInfo::admDelActivityInfo($limitRobInfo['id'], ActivityInfo::ACTIVITY_TYPE_LIMIT_TIME_ROB, AllActivityInfo::ALL_ACTIVITY_TYPE_FLASH_SALE);
			}
		}

		if ($limitRobInfos) {
			$rob_ids = array_column($limitRobInfos, 'id');
			$goods_ids = array_column($limitRobInfos, 'goods_id');

			mLimitTimeRobbing::updateRobbing(['status' => mLimitTimeRobbing::STATUS_DEL], ['id' => $rob_ids]);
			LimitTimeRobbingSku::update(['status' => LimitTimeRobbingSku::STATUS_DEL], ['robbing_id' => $rob_ids]);

			Activitys::setMultiRobbing($goods_ids);
		}
	}



    public static function saveSkuInfos($date_time_start, $date_time_end, $goods_id, $shop_id, $admin_id, $skustock, $flashSaleId)
    {
        if (self::is_can_save($date_time_start, $date_time_end, [])) {
            mLimitTimeRobbing::saveTimeRobings($date_time_start, $date_time_end, $goods_id, $shop_id, $admin_id, $skustock, $flashSaleId);
        } else {
            self::setMsg('时间设置区间有误');
            return false;
        }

    }

    private static function is_can_save($date_time_start, $date_time_end, $map = [])
    {
        // 活动还未开始
		$filter = [
			'OR' => [
				'AND #1' => [
					'start_time[<]' => $date_time_start,
					'end_time[>]' => $date_time_start,
				],
				'AND #2' => [
					'start_time[<]' => $date_time_end,
					'end_time[>]' => $date_time_end,
				],
			],
			'status' => [
				mLimitTimeRobbing::STATUS_NORMAL,
				mLimitTimeRobbing::STATUS_ONLY_SKU,
			]
		];

		if ($map) {
			$filter = array_merge($filter, $map);
		}

        return mLimitTimeRobbing::getFiledsByFilter(['goods_id'], $filter) ? false : true;
    }

    public static function admAddFlashSale($data)
    {
        return mFlashSale::addFlashSale($data);
    }

    public static function admUpdateFlashSale($flashSaleId, $data)
    {
        return mFlashSale::updateFlashSale($flashSaleId, $data);
    }

	public static function saveAllActivity($flashSaleId)
	{
		$limitRobInfos = self::getLimitRobInfos($flashSaleId);
		list($activityGoodsData, $activitySkuData) = self::formatAllActivityData($limitRobInfos);

		return AllActivityInfo::admUpdateActivityInfo(
			$flashSaleId,
			ActivityInfo::ACTIVITY_TYPE_LIMIT_TIME_ROB,
			$activityGoodsData,
			$activitySkuData,
			AllActivityInfo::ALL_ACTIVITY_TYPE_FLASH_SALE,
			true
		);

//		}
	}

	private static function formatAllActivityData($limitRobInfos)
	{
		$activityGoodsData = [];
		$activitySkuData = [];
		$currentTime = date('Y-m-d H:i:s');
		foreach ($limitRobInfos as $limitRobInfo) {
			$activityGoodsData[] = [
				'activity_id' => $limitRobInfo['flash_sale_id'],
				'shop_id' => $limitRobInfo['shop_id'],
				'goods_id' => $limitRobInfo['goods_id'],
				'type' => ActivityInfo::ACTIVITY_TYPE_LIMIT_TIME_ROB,
				'start_time' => $limitRobInfo['start_time'],
				'end_time' => $limitRobInfo['end_time'],
				'status' => AllActivityGoods::STATUS_NORMAL,
				'preview_start_time' => $limitRobInfo['start_time'],
				'real_start_time' => $limitRobInfo['start_time'],
				'real_end_time' => $limitRobInfo['end_time'],
			];
			$skuIds = array_column($limitRobInfo['rob_sku'], 'sku_id');
			$skuList = Sku::Sku4Order($skuIds);
			foreach ($limitRobInfo['rob_sku'] as $skuInfos) {
				$activitySkuData[] = [
					'activity_id' => $limitRobInfo['flash_sale_id'],
					'shop_id' => $skuInfos['shop_id'],
					'type' => ActivityInfo::ACTIVITY_TYPE_LIMIT_TIME_ROB,
					'goods_id' => $skuInfos['goods_id'],
					'sku_id' => $skuInfos['sku_id'],
					'status' => AllActivitySku::STATUS_NORMAL,
					'is_activity_stock' => mAllActivitySku::USE_ACTIVITY_STOCK,
					'activity_stock' => $skuInfos['start_stock'],
					'actual_stock' => $skuInfos['promo_stock'],
					'activity_price' => $skuInfos['buy_price'],
					'is_activity_commission' => mAllActivitySku::NOT_USE_COMMISSION,
					'activity_commission' => $limitRobInfo['commission'],
					'start_time' => $limitRobInfo['start_time'],
					'end_time' => $limitRobInfo['end_time'],
					'preview_start_time' => $limitRobInfo['start_time'],
					'real_start_time' => $limitRobInfo['start_time'],
					'real_end_time' => $limitRobInfo['end_time'],
					'limit_buy_count' => $limitRobInfo['buy_limit'],
					'activity_allowance' => $skuList[$skuInfos['sku_id']]['ori_price'] - $skuInfos['buy_price'],
				];
			}
		}

		return [$activityGoodsData, $activitySkuData];

	}
	private static function getLimitRobInfos($flashSaleId)
	{
		$limitRobInfos = mLimitTimeRobbing::getFlashSaleIngGoodsInfos($flashSaleId, '*', true);
		return  self::getLimitRobSkuInfos($limitRobInfos);
	}

	private static function getLimitRobSkuInfos($limitRobInfos)
	{
		$robIds = array_column($limitRobInfos, 'id');
		$robSkuInfos = LimitTimeRobbingSku::getInfosByRobID($robIds, false, true);
		foreach ($limitRobInfos as $key =>  $limitRobInfo) {
			$limitRobInfos[$key]['rob_sku'] = $robSkuInfos[$limitRobInfo['id']];
		}
		return $limitRobInfos;
	}

}